package demo.controller;

import demo.dao.UserMapper;
import jdbc.InputUtil;
import jdbc.UserInfo;

import java.util.Scanner;

public class UserController2 {
    private final UserMapper userMapper;

    public UserController2() {
        this.userMapper = new UserMapper();
    }

    public void start(){
        System.out.println("欢迎使用用户管理系统");
        System.out.println("请输入要是操作的编号");
        System.out.println("[1]：注册");
        System.out.println("[2]：登录");
        System.out.println("[3]：修改密码");
        Scanner scanner = new Scanner(System.in);
        String num = scanner.nextLine();
        switch (num){
            case "1":
                regUser();
                break;
            case "2":
                loginUser();
                break;
            case "3":
                changPWD();
                break;
            default:
                System.out.println("编号有误");
        }
    }

    public void regUser(){
        UserInfo userinfo = InputUtil.getInputObject(new UserInfo(), "欢迎注册");
        if (userMapper.findByUsername(userinfo.getUsername())!=null){
            System.out.println("用户存在");
        }else {
            userMapper.insert(userinfo);
            System.out.println("成功");
        }
    }

    public void loginUser(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("欢迎登录");
        System.out.println("输入用户名");
        String username = scanner.nextLine();
        System.out.println("新密码");
        String password = scanner.nextLine();

        UserInfo userInfo = userMapper.findByUsername(username);
        if (userInfo==null||!userInfo.getPassword().equals(password)){
            System.out.println("用户名或密码错误，登录失败");
        }else {
            System.out.println("登录成功，欢迎回来"+userInfo.getNickname());
        }
    }

    public void changPWD(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("修改密码");
        System.out.println("用户名");
        String username = scanner.nextLine();
        System.out.println("旧密码");
        String oldPassword = scanner.nextLine();
        System.out.println("新密码");
        String newPassword = scanner.nextLine();

        UserInfo userInfo = userMapper.findByUsername(username);
        if (userInfo==null||!userInfo.getPassword().equals(oldPassword)){
            System.out.println("信息错误，重新输入");
        }else {
            userInfo.setPassword(newPassword);
            userMapper.update(userInfo);
            System.out.println("修改成功");
        }
    }




    public static void main(String[] args) {
        UserController2 userController2 = new UserController2();
        userController2.start();
    }
}
